#!/bin/sh
#Script parameters

#A subroutine for printing the proper usage to the screen
printusage ()
{
  echo "usage: $0 regcm.in"
  echo "  where regcm.in is the namelist file for the run that you want to postprocess"
  exit
}

#TODO: Check validity and occurrence of command line arguments
if [ -z "$1" ]; then
  printusage
fi
if [ ! -e "$1" ]; then
  echo "Error: '$1' does not exist"
  printusage
fi

#Set the regcm.in file
REGCMIN=$1

#The only argument from the command line: the regcm.in file
PID=$$

##########Control variables################

#A couple of variables to make writing filenames in this script possible
endstr="0100"
endstrd="010100"
us="_"

#Have a high wake rate to make sure that ICBC daemon sees files
#before recmppdaemon removes them
SLEEPTIME=15


echo "Parsing $REGCMIN..."
##################### Reading regcm.in ########################
#Use grep and sed to pull the experiment name from the regcm.in file
EXPNAME=`grep -i domname $REGCMIN | sed "s/[Dd][Oo][Mm][Nn][Aa][Mm][Ee]\s*=\s*'\(.*\)',/\1/"`
EXPNAME=`echo $EXPNAME`

#Use grep and sed to pull the output directory and the start/end dates
#from the regcm.in file
#Start date of run
IDATE1=`grep -i "globidate1" $REGCMIN | sed "s/[Gg][Ll][Oo][Bb][Ii][Dd][Aa][Tt][Ee]1\s*=\s*\(.*\),/\1/"`
IDATE1=`echo $IDATE1`
#End date of run; inverse search for glob to avoid globidate2
#IDATE2=`grep -i "idate2" $REGCMIN | grep -iv glob |  sed "s/[Ii][Dd][Aa][Tt][Ee]2\s*=\s*\(.*\),/\1/"`
IDATE2=`grep -i "globidate2" $REGCMIN |  sed "s/[Gg][Ll][Oo][Bb][Ii][Dd][Aa][Tt][Ee]2\s*=\s*\(.*\),/\1/"`
IDATE2=`echo $IDATE2`
#Output directory (allow for no comma at the end, since it is the last item in 
#the namelist
OUTDIR=`grep -i dirout $REGCMIN | sed "s/[Dd][Ii][Rr][Oo][Uu][Tt]\s*=\s*'\(.*\)',*/\1/"`
OUTDIR=`echo $OUTDIR`
INPDIR=`grep -i dirglob $REGCMIN | sed "s/[Dd][Ii][Rr][Gg][Ll][Oo][Bb]\s*=\s*'\(.*\)',*/\1/"`
INPDIR=`echo $INPDIR`
echo $INPDIR

#TAO
echo "Dates: $IDATE1 $IDATE2"

#Assume that icbc lives in Bin, which is a directory up from the output
#directory
ICBCBIN="$OUTDIR/../Bin/icbc"


#Parse the start and end date strings
STARTYEAR=`echo $IDATE1 | sed "s/\(\w\w\w\w\)\w\w\w\w\w\w/\1/"`
STARTMONTH=`echo $IDATE1 | sed "s/\w\w\w\w\(\w\w\)\w\w\w\w/\1/"`
ENDYEAR=`echo $IDATE2 | sed "s/\(\w\w\w\w\)\w\w\w\w\w\w/\1/"`
ENDMONTH=`echo $IDATE2 | sed "s/\w\w\w\w\(\w\w\)\w\w\w\w/\1/"`

##################### End Reading regcm.in ####################

################# Run ICBC on the first year ###################
YEAR0=$STARTYEAR
YEAR1=`expr $STARTYEAR + 1`
MON0=$STARTMONTH
MON1=$STARTMONTH
GID0="$YEAR0$MON0$endstr"
GID1="$YEAR1$MON1$endstr"
echo "\tCreating files for ${GID0}-${GID1}..."
cat $REGCMIN | sed "s/\(globidate1\s*=\s*\).*,/\1$GID0,/" | sed "s/\(globidate2\s*=\s*\).*,/\1$GID1,/" > regcm.$PID
$ICBCBIN regcm.$PID

#remove the regcm.in
rm regcm.$PID
echo "\t...done"
################# End Run ICBC on the first year ###############




##################### Main loop ###############################
#Loop through all years
#Run icbc to make sure that at least one year of data exists
#ahead of the current year
#Wait for startmonth of each year to be created; when it is,
#run icbc for the next year, and delete files from the previous year
for year in `seq $STARTYEAR $ENDYEAR`
do
    YEARM1=`expr $year - 1`
    YEAR0=`expr $year + 1`
    YEAR1=`expr $year + 2`
    MON0=$STARTMONTH
    MON1=$STARTMONTH
    #If this is the last year, then make the end year
    #and end month the final 
    if [ "$YEAR1" -ge "$ENDYEAR" ]; then
      YEAR1=$ENDYEAR
      MON1=$ENDMONTH
    fi

    ##################### Waiting loop ############################
    #Enter a while loop that waits for startmonth to be completed
    #icbc the next year when it is
    MONTHREADY=0
    while [ "$MONTHREADY" -ne "1" ]
    do
      #The RegCM output file for the requested month
      nextfile="${OUTDIR}/${EXPNAME}_ATM.${year}${STARTMONTH}${endstr}.nc"
#      echo $nextfile
      if [ -s $nextfile ]; then
        MONTHREADY=1
      else
        MONTHREADY=0
      fi
      #Wait SLEEPTIME seconds before trying again
      if [ $MONTHREADY -ne "1" ];then
        echo "Waiting for $STARTMONTH/$year to be ready..."
        sleep $SLEEPTIME
      fi
    done
    ################# End Waiting loop ############################

    ################# Run ICBC on the next year ###################
    GID0="$YEAR0$MON0$endstr"
    GID1="$YEAR1$MON1$endstr"
    echo "\tCreating files for ${GID0}-${GID1}..."
    cat $REGCMIN | sed "s/\(globidate1\s*=\s*\).*,/\1$GID0,/" | sed "s/\(globidate2\s*=\s*\).*,/\1$GID1,/" > regcm.$PID
    $ICBCBIN regcm.$PID

    #TODO: Check that all files were created

    #remove the regcm.in
    rm regcm.$PID
    echo "\t...done"
    ################# End Run ICBC on the next year ###############

    ########## Delete ICBC files from the previous year ###########
    #Generate a list of months that represent the 
    #previous 12 months
    if [ "$MON0" -eq "1" ];then
      MLIST=`seq --equal-width 1 12`
    else
      MLIST1=`seq --equal-width ${MON0} 12`
      MM1=`expr $MON0 - 1`
      MLIST2=`seq --equal-width 1 ${MM1}`
      MLIST="${MLIST1} ${MLIST2}"
    fi
    #Go through each month in the list
    for month in $MLIST
    do
      #Increment the year if the month list has
      #wrapped past 12
      if [ "$month" -lt "$MON0" ]; then
        yearstr=$year
      else
        yearstr=$YEARM1
      fi
      #Set the file name
      fname="${INPDIR}/${EXPNAME}_ICBC.${yearstr}${month}0100.nc"
      #Delete the file
      if [ -s $fname ]; then
        echo "\t\t...deleting ${fname}"
        rm $fname
      fi
        echo "\t${fname}"
    done
    ####### End Delete ICBC files from the previous year ##########

done
################# End Main loop ###############################
